<?php

namespace app\model\ec;

use app\eslib\EsUtils;
use app\model\esxsys\SearchesModel;
use app\model\ModelUtils;
use think\facade\Cache;
use think\facade\Db;
use think\Model;

class GoodsModel extends Model
{
    /**
     * 该表将与模型关联。
     * @var string
     */
    protected $table = 'ec_goods';

    // 开启自动时间戳（默认为整型int）
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    /**
     * 返回 状态数据 访问器的值
     * @return string
     */
    public function getStatusDataAttr(): array
    {
        $data = [
            ['text' => '正常', 'value' => 1],
            ['text' => '禁用', 'value' => 0],
        ];
        return $data;
    }

    /**
     * 返回 状态 访问器的值
     * @return string
     */
    public function getStatusTextAttr($value, $data)
    {
        $value = $data['status'];
        if (is_numeric($value)) {
            $value = intval($value);
        }
        $data = (array) $this->getStatusDataAttr();
        $result = array_filter($data, function ($v) use ($value) {
            return $v['value'] == $value;
        }, ARRAY_FILTER_USE_BOTH);
        return $result ? current($result)['text'] : $value;
    }

    /**
     * 使用视图查询
     */
    public function scopeDbView($query)
    {
        return $query->table('v_ec_goods');
    }


    /**
     * 商品详情页 - 推荐列表
     * 规则：同类商品，价格最低前50个，随机读取几个
     */
    public static function getLitForGoodsRecommend($categoryId, $count = 5)
    {
        $table = (new static())->table;
        $cacheKey = "{$table}_goods_recommend_{$categoryId}";
        $data = Cache::get($cacheKey);
        if (!$data) {
            $field = 'id, goods_name, icon, price';
            $data = Db::table($table)->where('category_id', $categoryId)->where('status', 1)->order('price')->limit(50)->field($field)->select();
            Cache::set($cacheKey, $data);
            ModelUtils::cachePut($table, $cacheKey);
        }

        return $data ? array_rand($data, $count) : [];
    }

    public static function getListForApi($mode, $categoryId, $searchText, $sort, $pageSize, $filter = [])
    {
        if ($searchText) {
            // 保存关键词到搜索记录中
            SearchesModel::addSearch($searchText, 'goods', 0);
        }

        $field = '*';
        if ($mode) {
            // 获取促销商品列表
            $field = 'id, goods_name, icon, price, index_carousel_main_image';
            switch ($mode) {
                case 'index_carousel_main':
                    // 首页 - 轮播图片
                    // ?_mode=index_carousel_main&page=1&page_size=6
                    $where[] = ['is_promotion_expiring', '=', 1];
                    break;
                case 'flush':
                    // 首页 - 限时抢购
                    // ?_mode=flush&page=1&page_size=6
                    $where[] = ['is_promotion_flush', '=', 1];
                    break;
                case 'expiring':
                    // 首页 - 最近临期
                    // ?_mode=expiring&page=1&page_size=6
                    $where[] = ['is_promotion_expiring', '=', 1];
                    break;
                case 'hot':
                    // 首页 - 热卖精选（热销）
                    // ?_mode=hot&page=1&page_size=6
                    $where[] = ['is_promotion_hot', '=', 1];
                    break;
                case 'selection':
                    // 首页 - 大牌特卖
                    // ?_mode=selection&page=1&page_size=6
                    $where[] = ['is_promotion_selection', '=', 1];
                    break;
                case 'recommend':
                    // 首页 - 品牌推荐（轮播）
                    // ?_mode=selection&page=1&page_size=6
                    $where[] = ['is_promotion_recommend', '=', 1];
                    break;
                case 'new':
                    // 首页 - 最新商品
                    // ?_mode=new&page=1&page_size=6
                    $where[] = ['is_promotion_new', '=', 1];
                    break;
                default:
                    return EsUtils::stdMessage(false, '促销类型无效');
                    break;
            }
        }
        // 排序：综合推荐、销量、价格 ?sort=recommand,sales,price&cid=1&filter=...&search=
        $orderBy = 'id desc';
        switch ($sort) {
            case 'recommand': // 综合推荐
                $orderBy = 'sort, id desc';
                break;
            case 'sales': // 高销量
                $orderBy = 'stat_sales_quantity desc';
                break;
            case 'cheap': // 低价
                $orderBy = 'price asc';
                break;
            case 'expensive': // 高价
                $orderBy = 'price desc';
                break;
            default:
                break;
        }

        $data = GoodsModel::dbView()->where(function ($query) use ($categoryId, $searchText, $filter) {
            if ($categoryId > 0) {
                $query->where('category_id', $categoryId);
            }
            if ($searchText) {
                $query->where(function ($query) use ($searchText) {
                    $query->where('id', intval($searchText))->whereOr('goods_name', 'like', "%{$searchText}%");
                });
            }
            if ($filter) {
                // 筛选：发货城市（全国、某城市）、价格区间、品牌、净含量 ?filter=y&city=某市&price=1-100&brand=1&weight=500ml-1L
                if (isset($filter['brand'])) {
                    $query->where('brand_id', $filter['brand']);
                }
                if (isset($filter['price'])) {
                    $priceInfo = array_filter(explode('-', $filter['price']));
                    if (isset($priceInfo[0])) {
                        $query->where('price', '>=', $priceInfo[0]);
                    }
                    if (isset($priceInfo[1])) {
                        $query->where('price', '<=', $priceInfo[1]);
                    }
                }
            }
        })->field($field)->order($orderBy)->paginate($pageSize);

        return EsUtils::stdMessage(true, '', $data);
    }

    /**
     * 获取商品数据
     */
    public static function getDataForLomall($id)
    {
        $cacheKey = "ec_goods_{$id}";
        $data = Cache::get($cacheKey);
        if ($data) {
            return EsUtils::stdMessage(true, '', $data);
        }
        $model = self::find($id);
        if (!$model) {
            return EsUtils::stdMessage(false, '商品不存在');
        }
        // 获取商品的同商家(Merchant)+同品牌(Brand)+同类别(Category)的商品列表（作为规格类别）（借鉴京东商城）
        $field = 'id, goods_name, icon';
        $categoriesList = self::where('mch_id', $model->mch_id)->where('category_id', $model->category_id)->where('brand_id', $model->brand_id)->field($field)->limit(4)->select();
        // 获取规格
        $specsList = SkusModel::where('goods_id', $id)->field('id, sku_no, price, quantity, icon, expired_date')->limit(4)->select();
        if ($model->carousel_images) {
            $model->carousel_images_list = explode(',', $model->carousel_images);
        }
        $data = [
            'data' => $model,
        ];
        $data['categories_data'] = $categoriesList;
        $data['specs_data'] = $specsList;
        Cache::set($cacheKey, $data, 30);
        return EsUtils::stdMessage(true, '', $data);
    }
}
